from rest_framework.views import APIView
from bddjango import BaseListView, APIResponse
from bddjango import get_field_names_by_model
from bddjango import conv_queryset_to_dc_ls
from bddjango import my_api_assert_function
from bddjango import get_base_serializer
from bddjango.baseSearchView import BaseFullTextSearchMixin
from pgZhSearch import search_rank_field_name, search_vector_field_name
from . import models


# --- APIView 综合检索1
class Question1(APIView):
    """
    问题检索
    - 启用全文检索: `search_keywords`

    GET http://127.0.0.1:8000/api/search/Question1/?search_keywords=劳动纠纷
    """
    queryset = models.Question.objects.filter(is_active=True)
    list_fields = ['id', 'fen_lei_ming', 'wen_ti', search_rank_field_name]
    retrieve_fields = list_fields
    serializer_class = get_base_serializer(queryset, list_fields)

    def get(self, request, *args, **kwargs):
        search_keywords = request.GET.get('search_keywords')
        my_api_assert_function(search_keywords, 'search_keywords不能为空!')
        # qs_ls = models.Question.objects.search(search_keywords)       # 搜索全部
        qs_ls = self.queryset.search(search_keywords)
        ret = conv_queryset_to_dc_ls(qs_ls.values(*self.list_fields)[:5])
        return APIResponse(ret)


# --- 综合检索2
class Question(BaseFullTextSearchMixin, BaseListView):
    """
    问题表
    - 启用全文检索: `search_keywords`

    GET /api/search/Question/?search_keywords=继承遗产&fen_lei_ming=农业农村土地
    """
    queryset = models.Question

    all_fields = get_field_names_by_model(queryset, exclude_fields=[search_vector_field_name])
    retrieve_fields = list_fields = all_fields + [search_rank_field_name]


class TestModel(BaseFullTextSearchMixin, BaseListView):
    """
    测试表
    - 启用全文检索: `search_keywords`

    GET /api/search/TestModel/?search_keywords=随着党中央政策的发展,党校马克思主义哲学教学受到越来越广泛的关注
    """
    queryset = models.TestModel
    auto_generate_serializer_class = True
    base_fields = ['id', 'title', search_rank_field_name]


